package com.mjgy.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;

import com.common.utils.R;
import com.mjgy.entity.CommodityEntity;
import com.mjgy.entity.DealEntity;
import com.mjgy.service.DealService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("dealService")
@Transactional
public class DealServiceImpl implements DealService {

    @Autowired
    private EntityManager em;

    @Override
    public R saveDeal(Long userId, Long commodityId, String receiver, String address, String phone) {
        DealEntity deal = new DealEntity();
        deal.setUserId(userId);
        deal.setCommodityId(commodityId);
        deal.setReceiver(receiver);
        deal.setAddress(address);
        deal.setPhone(phone);
        deal.setState(1);
        em.persist(deal);
        return R.success();
	}

    @Override
    public R getDealList(Long userId, Integer page, Integer pageSize) {
        if (page != null && pageSize != null) {
            page = (page - 1) * pageSize;
        }
        StringBuilder sql = new StringBuilder();
        sql.append("from DealEntity where userId = :userId");
        Query query = em.createQuery(sql.toString());
        query.setParameter("userId", userId);
        if (page != null && pageSize != null) {
            query.setFirstResult(page);
            query.setMaxResults(pageSize);
        }
        List<DealEntity> result = query.getResultList();
        for (DealEntity dealEntity : result) {
			Long commodityId = dealEntity.getCommodityId();
			CommodityEntity commodity = em.find(CommodityEntity.class, commodityId);
			dealEntity.setCommodity(commodity);
		}
        return R.success().put("data", result);
    }
    
}